<template>
  <view class="order-container">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <view class="nav-left" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="nav-center">
        <text class="nav-title">确认订单</text>
      </view>
      <view class="nav-right"></view>
    </view>
    
    <!-- 配送信息 -->
    <view class="delivery-section">
      <view class="section-title">配送信息</view>
      <view class="delivery-form">
        <view class="form-item address-selector" @click="selectAddress">
          <text class="form-label">收货地址</text>
          <view class="address-display">
            <view v-if="selectedAddress" class="selected-address">
              <view class="address-header">
                <text class="contact-name">{{ selectedAddress.name }}</text>
                <text class="contact-phone">{{ selectedAddress.phone }}</text>
                <view class="default-tag" v-if="selectedAddress.isDefault">
                  <text class="default-text">默认</text>
                </view>
              </view>
              <text class="address-detail">{{ selectedAddress.address }}</text>
            </view>
            <view v-else class="no-address">
              <text class="placeholder-text">请选择收货地址</text>
            </view>
            <text class="arrow-icon">></text>
          </view>
        </view>
        <view class="form-item">
          <text class="form-label">预约送达时间</text>
          <view class="time-selector">
            <picker 
              mode="date" 
              :value="selectedDate"
              :start="today"
              @change="onDateChange"
            >
              <view class="date-picker">
                <text class="date-text">{{ selectedDate || '选择日期' }}</text>
                <text class="picker-icon">></text>
              </view>
            </picker>
            <picker 
              mode="selector" 
              :range="timeSlots"
              :value="selectedTimeIndex"
              @change="onTimeChange"
            >
              <view class="time-picker">
                <text class="time-text">{{ selectedTimeSlot || '选择时间段' }}</text>
                <text class="picker-icon">></text>
              </view>
            </picker>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 订单详情 -->
    <view class="order-section">
      <view class="section-title">订单详情</view>
      
      <!-- ⭐ 单商品订单 -->
      <view v-if="!isMultiItem" class="order-item">
        <view class="store-info">
          <text class="store-name">{{ orderData.storeName || '商家入驻中' }}</text>
        </view>
        <view class="food-detail">
          <image 
            :src="orderData.image" 
            mode="aspectFill"
            class="food-image"
          />
          <view class="food-info">
            <text class="food-name">{{ orderData.name }}</text>
            <text class="food-options">{{ orderData.spice }} · {{ orderData.quantity }}份</text>
            <view class="food-price">
              <text class="price">¥{{ orderData.totalPrice }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- ⭐ 多商品订单 -->
      <view v-else class="multi-order-items">
        <view class="store-info">
          <text class="store-name">{{ multiOrderData.merchantName || '商家入驻中' }}</text>
        </view>
        <view 
          v-for="(item, index) in multiOrderData.items" 
          :key="index"
          class="food-detail"
        >
          <image 
            :src="item.image" 
            mode="aspectFill"
            class="food-image"
          />
          <view class="food-info">
            <text class="food-name">{{ item.name }}</text>
            <text class="food-options">{{ item.spiceLevel }} · {{ item.quantity }}份</text>
            <view class="food-price">
              <text class="price">¥{{ (item.price * item.quantity).toFixed(2) }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- ⭐ 费用明细 -->
    <view class="price-detail-section">
      <view class="price-row">
        <text class="price-label">商品总价</text>
        <text class="price-value">¥{{ goodsTotalPrice.toFixed(2) }}</text>
      </view>
      <view class="price-row">
        <text class="price-label">配送费</text>
        <text class="price-value">¥{{ deliveryFee.toFixed(2) }}</text>
      </view>
      <view class="price-row" v-if="packagingFee > 0">
        <text class="price-label">打包费</text>
        <text class="price-value">¥{{ packagingFee.toFixed(2) }}</text>
      </view>
    </view>
    
    <!-- 备注 -->
    <view class="notes-section">
      <view class="section-title">备注</view>
      <textarea 
        class="notes-input" 
        placeholder="添加备注（选填）"
        v-model="notesContent"
        maxlength="100"
      ></textarea>
    </view>
    
    <!-- 底部总计和下单按钮 -->
    <view class="bottom-section">
      <view class="total-info">
        <text class="total-label">实付金额</text>
        <text class="total-price">¥{{ displayTotalPrice }}</text>
      </view>
      <button 
        class="order-btn" 
        :disabled="!canSubmit"
        @click="submitOrder"
      >
        立即下单
      </button>
    </view>
    
    <!-- 自定义弹窗 -->
    <CustomModal ref="customModal" />
  </view>
</template>

<script>
import orderService from '../../services/order.js'
import addressService from '../../services/address.js'
import groupBuyingService from '../../services/group-buying.js'
import { smartBack } from '../../utils/navigation.js'
import CustomModal from '../../components/CustomModal.vue'

export default {
  components: {
    CustomModal
  },
  data() {
    return {
      statusBarHeight: 0,
      deliveryInfo: {
        scheduledTime: ''
      },
      selectedAddress: null,
      timeSlots: [],
      selectedTimeIndex: 0,
      selectedDate: '',
      selectedTimeSlot: '',
      today: '',
      orderType: 'normal',  // normal | create_group | join_group | multi
      isMultiItem: false,   // 是否为多商品订单
      deliveryFee: 0,       // ⭐ 配送费
      packagingFee: 0,      // ⭐ 打包费（暂时为0）
      // 拼单相关数据
      groupData: {
        activityId: null,     // 参与拼单时的活动ID
        groupTitle: '',       // 发起拼单的标题
        groupSize: 0,         // 发起拼单的人数
        durationHours: 0      // 发起拼单的时长
      },
      // 单商品订单数据
      orderData: {
        foodId: null, // 商品ID
        merchantId: null, // 商家ID
        storeName: '',
        name: '',
        image: '',
        price: '',
        quantity: 1,
        spice: '不辣',
        totalPrice: '0',
        notes: ''
      },
      // 多商品订单数据
      multiOrderData: {
        merchantId: null,
        merchantName: '',
        items: [],  // [{ id, name, image, price, quantity, spiceLevel }]
        totalPrice: 0,
        notes: ''
      }
    }
  },
  computed: {
    // ⭐ 商品总价
    goodsTotalPrice() {
      if (this.isMultiItem) {
        return this.multiOrderData.totalPrice
      } else {
        return parseFloat(this.orderData.totalPrice || 0)
      }
    },
    
    // ⭐ 实付金额（商品总价 + 配送费 + 打包费）
    displayTotalPrice() {
      return (this.goodsTotalPrice + this.deliveryFee + this.packagingFee).toFixed(2)
    },
    
    canSubmit() {
      return this.selectedAddress && this.goodsTotalPrice > 0
    },
    
    // 备注内容（用于 v-model）
    notesContent: {
      get() {
        return this.isMultiItem ? this.multiOrderData.notes : this.orderData.notes
      },
      set(value) {
        if (this.isMultiItem) {
          this.multiOrderData.notes = value
        } else {
          this.orderData.notes = value
        }
      }
    }
  },
  onLoad(options) {
    this.getStatusBarHeight()
    
    // 识别订单类型
    if (options.type === 'create_group') {
      this.orderType = 'create_group'
      this.isMultiItem = false
      this.groupData.groupTitle = decodeURIComponent(options.groupTitle || '')
      this.groupData.groupSize = parseInt(options.groupSize || 2)
      this.groupData.durationHours = parseInt(options.durationHours || 24)
      console.log('订单类型：发起拼单', this.groupData)
      this.loadOrderData(options)
    } else if (options.type === 'join_group') {
      this.orderType = 'join_group'
      this.isMultiItem = false
      this.groupData.activityId = parseInt(options.activityId)
      console.log('订单类型：参与拼单', this.groupData)
      this.loadOrderData(options)
    } else if (options.type === 'multi') {
      // ⭐ 多商品订单
      this.orderType = 'multi'
      this.isMultiItem = true
      console.log('订单类型：多商品订单')
      this.loadMultiOrderData()
    } else {
      // 普通单商品订单
      this.orderType = 'normal'
      this.isMultiItem = false
      console.log('订单类型：普通下单')
      this.loadOrderData(options)
    }
    
    this.initDateAndTime()
    this.initDefaultAddress()
  },
  onShow() {
    // 检查是否有地址选择数据
    this.checkAddressSelection()
  },
  methods: {
    // 获取状态栏高度
    getStatusBarHeight() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 20
    },
    
    // 加载订单数据（单商品）
    loadOrderData(options) {
      console.log('订单页面 - 接收参数:', options)
      if (options.foodId) this.orderData.foodId = parseInt(options.foodId)
      if (options.merchantId) this.orderData.merchantId = parseInt(options.merchantId)
      if (options.storeName) this.orderData.storeName = decodeURIComponent(options.storeName)
      if (options.name) this.orderData.name = decodeURIComponent(options.name)
      if (options.image) this.orderData.image = decodeURIComponent(options.image)
      if (options.price) this.orderData.price = decodeURIComponent(options.price)
      if (options.quantity) this.orderData.quantity = parseInt(options.quantity)
      if (options.spice) this.orderData.spice = decodeURIComponent(options.spice)
      if (options.totalPrice) this.orderData.totalPrice = decodeURIComponent(options.totalPrice)
      if (options.deliveryFee) this.deliveryFee = parseFloat(options.deliveryFee)  // ⭐ 接收配送费
    },
    
    // ⭐ 加载多商品订单数据
    loadMultiOrderData() {
      try {
        const orderCart = uni.getStorageSync('orderCart')
        console.log('读取购物车数据:', orderCart)
        
        if (!orderCart || !orderCart.items || orderCart.items.length === 0) {
          uni.showToast({
            title: '购物车数据为空',
            icon: 'none',
            duration: 2000
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 2000)
          return
        }
        
        this.multiOrderData = {
          merchantId: orderCart.merchantId,
          merchantName: orderCart.merchantName,
          items: orderCart.items,
          totalPrice: orderCart.totalPrice,
          notes: ''
        }
        
        // ⭐ 接收配送费
        if (orderCart.deliveryFee !== undefined) {
          this.deliveryFee = parseFloat(orderCart.deliveryFee)
        }
        
        console.log('多商品订单数据已加载:', this.multiOrderData)
        console.log('配送费:', this.deliveryFee)
        
        // 清除本地存储（避免重复使用）
        uni.removeStorageSync('orderCart')
      } catch (error) {
        console.error('加载购物车数据失败:', error)
        uni.showToast({
          title: '加载订单数据失败',
          icon: 'none'
        })
      }
    },
    
    // 初始化日期和时间
    initDateAndTime() {
      const now = new Date()
      this.today = this.formatDate(now)
      this.generateTimeSlots()
    },
    
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    // 生成时间段选项（每2小时一个时间段）
    generateTimeSlots() {
      const slots = []
      const now = new Date()
      const currentHour = now.getHours()
      
      // 从当前时间开始，每2小时生成一个时间段
      for (let i = 0; i < 12; i++) { // 生成12个时间段（24小时）
        const hour = currentHour + (i * 2)
        if (hour >= 24) break
        
        const startHour = hour
        const endHour = hour + 2
        
        const startTime = `${startHour.toString().padStart(2, '0')}:00`
        const endTime = `${endHour.toString().padStart(2, '0')}:00`
        
        slots.push(`${startTime}-${endTime}`)
      }
      
      this.timeSlots = slots
    },
    
    // 日期选择
    onDateChange(e) {
      this.selectedDate = e.detail.value
      this.updateScheduledTime()
    },
    
    // 时间选择
    onTimeChange(e) {
      this.selectedTimeIndex = e.detail.value
      this.selectedTimeSlot = this.timeSlots[e.detail.value]
      this.updateScheduledTime()
    },
    
    // 更新预约时间
    updateScheduledTime() {
      if (this.selectedDate && this.selectedTimeSlot) {
        this.deliveryInfo.scheduledTime = `${this.selectedDate} ${this.selectedTimeSlot}`
      }
    },
    
    // 返回上一页
    goBack() {
      smartBack('/pages/home/home')
    },
    
    // 初始化默认地址
    async initDefaultAddress() {
      try {
        // 获取默认地址
        const response = await addressService.getDefaultAddress()
        if (response && response.data) {
          const addr = response.data
      this.selectedAddress = {
            id: addr.id,
            name: addr.name,
            phone: addr.phone,
            province: addr.province,
            city: addr.city,
            district: addr.district,
            address: `${addr.province}${addr.city}${addr.district}${addr.address}`,
            detailAddress: addr.address,
        isDefault: true
          }
          console.log('已加载默认地址:', this.selectedAddress)
        }
      } catch (error) {
        console.error('获取默认地址失败:', error)
        // 不显示错误提示，用户可以手动选择地址
      }
    },
    
    // 选择地址
    selectAddress() {
      uni.navigateTo({
        url: '/pages/address/address'
      })
    },
    
    // 检查地址选择
    checkAddressSelection() {
      // 从全局存储中获取选中的地址
      const selectedAddress = uni.getStorageSync('selectedAddress')
      console.log('检查地址选择:', selectedAddress)
      if (selectedAddress) {
        this.selectedAddress = selectedAddress
        console.log('地址已更新:', this.selectedAddress)
        // 清除存储
        uni.removeStorageSync('selectedAddress')
      }
    },
    
    // 处理地址选择
    handleAddressSelected(address) {
      this.selectedAddress = address
    },
    
    // 提交订单
    async submitOrder() {
      // 验证必填项
      if (!this.canSubmit) {
        uni.showToast({
          title: '请完善订单信息',
          icon: 'none'
        })
        return
      }
      
      if (!this.selectedAddress || !this.selectedAddress.id) {
        uni.showToast({
          title: '请选择收货地址',
          icon: 'none'
        })
        return
      }
      
      if (!this.selectedDate) {
        uni.showToast({
          title: '请选择配送日期',
          icon: 'none'
        })
        return
      }
      
      if (!this.selectedTimeSlot) {
        uni.showToast({
          title: '请选择配送时间段',
          icon: 'none'
        })
        return
      }
      
      // 验证订单数据
      if (this.isMultiItem) {
        if (!this.multiOrderData.merchantId || this.multiOrderData.items.length === 0) {
          uni.showToast({
            title: '订单信息不完整',
            icon: 'none'
          })
          return
        }
      } else {
        if (!this.orderData.foodId || !this.orderData.merchantId) {
          uni.showToast({
            title: '订单信息不完整',
            icon: 'none'
          })
          return
        }
      }
      
      try {
        // 根据订单类型调用不同逻辑
        if (this.orderType === 'create_group') {
          await this.createGroupAndOrder()
        } else if (this.orderType === 'join_group') {
          await this.joinGroupAndOrder()
        } else {
          await this.createNormalOrder()
        }
      } catch (error) {
        console.error('提交订单失败:', error)
        
        let errorMsg = '订单提交失败'
        if (error.message) {
          if (error.message.includes('401')) {
            errorMsg = '请先登录'
          } else if (error.message.includes('400')) {
            errorMsg = '订单信息有误，请检查'
          } else if (error.message.includes('404')) {
            errorMsg = '商品或地址不存在'
          } else {
            errorMsg = error.message
          }
        }
        
        uni.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 2000
        })
      }
    },
    
    // 普通下单
    async createNormalOrder() {
      let orderData
      let orderAmount
      
      if (this.isMultiItem) {
        // ⭐ 多商品订单
        orderData = {
          merchantId: this.multiOrderData.merchantId,
          addressId: this.selectedAddress.id,
          scheduledDeliveryDate: this.selectedDate,
          scheduledDeliveryTime: this.selectedTimeSlot,
          items: this.multiOrderData.items.map(item => ({
            foodId: item.id,
            quantity: item.quantity,
            spiceLevel: item.spiceLevel
          })),
          notes: this.multiOrderData.notes || ''
        }
        orderAmount = this.multiOrderData.totalPrice.toFixed(2)
        console.log('多商品下单 - 订单数据:', orderData)
      } else {
        // 单商品订单
        orderData = {
          merchantId: this.orderData.merchantId,
          addressId: this.selectedAddress.id,
          scheduledDeliveryDate: this.selectedDate,
          scheduledDeliveryTime: this.selectedTimeSlot,
          items: [{
            foodId: this.orderData.foodId,
            quantity: this.orderData.quantity,
            spiceLevel: this.orderData.spice
          }],
          notes: this.orderData.notes || ''
        }
        orderAmount = this.orderData.totalPrice
        console.log('单商品下单 - 订单数据:', orderData)
      }
      
      const response = await orderService.createOrder(orderData)
      const orderId = response.data.id
      
      // 弹出支付确认框（普通订单需要支付）
      this.$refs.customModal.show({
        type: 'success',
        title: '订单创建成功',
        content: `订单金额：¥${orderAmount}\n\n是否立即支付？`,
        confirmText: '立即支付',
        cancelText: '稍后支付',
        onConfirm: async () => {
          try {
            uni.showLoading({ title: '支付处理中...', mask: true })
            await new Promise(resolve => setTimeout(resolve, 1500))
            await orderService.payOrder(orderId, 'mock_payment')
            uni.hideLoading()
            
            uni.showToast({ title: '支付成功', icon: 'success', duration: 2000 })
            setTimeout(() => {
              uni.redirectTo({ url: `/pages/order-success/order-success?orderId=${orderId}` })
            }, 2000)
          } catch (payError) {
            uni.hideLoading()
            console.error('支付失败:', payError)
            uni.showToast({ title: '支付失败，请在订单列表重试', icon: 'none', duration: 2000 })
            setTimeout(() => {
              uni.redirectTo({ url: '/pages/orders/orders' })
            }, 2000)
          }
        },
        onCancel: () => {
          uni.showToast({ title: '订单已创建，请在订单列表支付', icon: 'none', duration: 2000 })
          setTimeout(() => {
            uni.redirectTo({ url: '/pages/orders/orders' })
          }, 2000)
        }
      })
    },
    
    // 发起拼单
    async createGroupAndOrder() {
      try {
        // 创建拼单活动（后端会在成团时自动创建订单）
        const activityData = {
          foodId: this.orderData.foodId,
          title: this.groupData.groupTitle,
          description: `${this.orderData.name}，${this.groupData.groupSize}人团，快来参加吧！`,
          minParticipants: this.groupData.groupSize,
          maxParticipants: this.groupData.groupSize,
          groupPrice: parseFloat(this.orderData.price),
          durationHours: this.groupData.durationHours,
          quantity: this.orderData.quantity,
          spiceLevel: this.orderData.spice
        }
        
        console.log('发起拼单 - 创建拼单活动:', activityData)
        
        const activityResponse = await groupBuyingService.createActivity(activityData)
        const activity = activityResponse?.data || activityResponse
        
        if (!activity || !activity.id) {
          throw new Error('拼单活动创建失败')
        }
        
        console.log('拼单活动创建成功:', activity)
        
        // 检查是否立即成团（特殊情况：1人团）
        if (activity.status === 'success') {
          // ✅ 1人团立即成团，后端已自动创建订单
          this.$refs.customModal.show({
            type: 'success',
            title: '拼单成功 🎉',
            content: '您的拼单已创建并立即成团，订单已自动生成，请前往订单页面支付',
            showCancel: false,
            confirmText: '查看订单',
            onConfirm: () => {
              uni.redirectTo({
                url: '/pages/orders/orders?filter=pending'
              })
            }
          })
        } else {
          // ❌ 多人团，还未成团，等待其他人参与
          const groupSize = this.groupData.groupSize
          const remaining = groupSize - 1 // 发起人算1人，还差 groupSize-1 人
          
          uni.showToast({ 
            title: `拼单创建成功，还差${remaining}人成团`, 
            icon: 'success',
            duration: 2000
          })
          
          setTimeout(() => {
            uni.redirectTo({
              url: `/pages/group-buying-detail/group-buying-detail?id=${activity.id}`
            })
          }, 2000)
        }
      } catch (error) {
        console.error('发起拼单失败:', error)
        
        this.$refs.customModal.show({
          type: 'danger',
          title: '发起失败',
          content: error.message || '发起拼单失败，请稍后重试',
          showCancel: false,
          confirmText: '知道了'
        })
      }
    },
    
    // 参与拼单
    async joinGroupAndOrder() {
      try {
        // 参与拼单（后端会在成团时自动创建订单）
        const joinResponse = await groupBuyingService.joinActivity(
          this.groupData.activityId,
          {
            quantity: this.orderData.quantity,
            spiceLevel: this.orderData.spice
          }
        )
        
        console.log('参与拼单成功:', joinResponse)
        
        // 检查拼单状态
        const joinData = joinResponse?.data || joinResponse
        
        if (joinData.status === 'success') {
          // ✅ 拼单已成团！后端已自动创建订单
          this.$refs.customModal.show({
            type: 'success',
            title: '拼单成功 🎉',
            content: '恭喜！拼单已成团，订单已自动生成，请前往订单页面支付',
            showCancel: false,
            confirmText: '查看订单',
            onConfirm: () => {
              uni.redirectTo({
                url: '/pages/orders/orders?filter=pending'
              })
            }
          })
        } else {
          // ❌ 还未成团，继续等待其他人参与
          const activity = joinData.activity || joinData
          const current = activity.currentParticipants || activity.current_participants || 0
          const max = activity.maxParticipants || activity.max_participants || 0
          const remaining = max - current
          
          uni.showToast({ 
            title: `参与成功，还差${remaining}人成团`, 
            icon: 'success',
            duration: 2000
          })
          
          setTimeout(() => {
            uni.redirectTo({
              url: `/pages/group-buying-detail/group-buying-detail?id=${this.groupData.activityId}`
            })
          }, 2000)
        }
      } catch (error) {
        console.error('参与拼单失败:', error)
        
        this.$refs.customModal.show({
          type: 'danger',
          title: '参与失败',
          content: error.message || '参与拼单失败，请稍后重试',
          showCancel: false,
          confirmText: '知道了'
        })
      }
    },
    
    // 显示支付对话框
    async showPaymentDialog(orderId, activityId, isGroupSuccess = false) {
      const title = isGroupSuccess ? '拼单成功！' : '订单创建成功'
      const content = isGroupSuccess 
        ? `拼单已成功！\n订单金额：¥${this.orderData.totalPrice}\n\n请尽快支付，支付后商家才能接单配送。`
        : `订单金额：¥${this.orderData.totalPrice}\n\n是否立即支付？`
      
      this.$refs.customModal.show({
        type: isGroupSuccess ? 'success' : 'confirm',
        title: title,
        content: content,
        confirmText: '立即支付',
        cancelText: '稍后支付',
        onConfirm: async () => {
          // 立即支付
          await this.payGroupOrder(orderId, activityId)
        },
        onCancel: () => {
          // 稍后支付
          uni.showToast({
            title: '请尽快在订单列表中支付',
            icon: 'none',
            duration: 2000
          })
          setTimeout(() => {
            if (isGroupSuccess) {
              // 如果是成团，跳转到订单列表
              uni.redirectTo({ url: '/pages/orders/orders' })
            } else {
              // 如果是发起拼单，跳转到拼单详情
              uni.redirectTo({
                url: `/pages/group-buying-detail/group-buying-detail?id=${activityId}`
              })
            }
          }, 2000)
        }
      })
    },
    
    // 支付拼单订单
    async payGroupOrder(orderId, activityId) {
      try {
        uni.showLoading({ title: '支付处理中...', mask: true })
        
        // 模拟支付延迟
        await new Promise(resolve => setTimeout(resolve, 1500))
        
        // 调用支付接口
        await orderService.payOrder(orderId, 'mock_payment')
        
        uni.hideLoading()
        
        uni.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000
        })
        
        // 支付成功后跳转到订单列表
      setTimeout(() => {
          uni.redirectTo({ url: '/pages/orders/orders' })
        }, 2000)
        
      } catch (error) {
        uni.hideLoading()
        console.error('支付失败:', error)
        
        this.$refs.customModal.show({
          type: 'danger',
          title: '支付失败',
          content: '支付失败，您可以稍后在订单列表中重新支付',
          showCancel: false,
          confirmText: '知道了',
          onConfirm: () => {
            uni.redirectTo({ url: '/pages/orders/orders' })
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.order-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 120rpx;
}

.status-bar {
  background: #fff;
}

.top-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  background: #fff;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #eee;
  
  .nav-left {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    
    .back-icon {
      font-size: 36rpx;
      color: #333;
      font-weight: bold;
    }
  }
  
  .nav-center {
    flex: 1;
    text-align: center;
    
    .nav-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }
  
  .nav-right {
    width: 60rpx;
  }
}

.delivery-section,
.order-section {
  background: #fff;
  margin: 20rpx 0;  // ⭐ 常规间距
  padding: 30rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 30rpx;
  }
}

.notes-section {
  background: #fff;
  margin: 20rpx 0 140rpx 0;  // ⭐ 只有备注区域底部留空间给固定按钮栏
  padding: 30rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 30rpx;
  }
}

.delivery-form {
  .form-item {
    margin-bottom: 30rpx;
    
    .form-label {
      display: block;
      font-size: 28rpx;
      color: #333;
      margin-bottom: 16rpx;
    }
    
    .form-input {
      width: 100%;
      height: 80rpx;
      background: #f8f9fa;
      border: 2rpx solid #e1e5e9;
      border-radius: 12rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
      color: #333;
      
      &:focus {
        border-color: #ff4757;
        background: #fff;
      }
    }
  }
  
  .address-selector {
    cursor: pointer;
    
    .address-display {
      display: flex;
      align-items: center;
      justify-content: space-between;
      min-height: 80rpx;
      background: #f8f9fa;
      border: 2rpx solid #e1e5e9;
      border-radius: 12rpx;
      padding: 20rpx;
      
      .selected-address {
        flex: 1;
        
        .address-header {
          display: flex;
          align-items: center;
          margin-bottom: 8rpx;
          
          .contact-name {
            font-size: 28rpx;
            font-weight: 600;
            color: #333;
            margin-right: 20rpx;
          }
          
          .contact-phone {
            font-size: 26rpx;
            color: #666;
            margin-right: 20rpx;
          }
          
          .default-tag {
            background: #ff4757;
            padding: 4rpx 12rpx;
            border-radius: 8rpx;
            
            .default-text {
              font-size: 20rpx;
              color: #fff;
              font-weight: 600;
            }
          }
        }
        
        .address-detail {
          font-size: 26rpx;
          color: #666;
          line-height: 1.4;
        }
      }
      
      .no-address {
        flex: 1;
        
        .placeholder-text {
          font-size: 28rpx;
          color: #999;
        }
      }
      
      .arrow-icon {
        font-size: 24rpx;
        color: #999;
        margin-left: 20rpx;
      }
    }
  }
  
  .form-row {
    display: flex;
    gap: 20rpx;
    
    .form-item {
      flex: 1;
      margin-bottom: 30rpx;
    }
  }
  
  .time-selector {
    display: flex;
    gap: 20rpx;
    
    .date-picker,
    .time-picker {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 80rpx;
      background: #f8f9fa;
      border: 2rpx solid #e1e5e9;
      border-radius: 12rpx;
      padding: 0 20rpx;
      
      .date-text,
      .time-text {
        font-size: 28rpx;
        color: #333;
      }
      
      .picker-icon {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}

.order-item,
.multi-order-items {
  .store-info {
    margin-bottom: 20rpx;
    
    .store-name {
      font-size: 28rpx;
      font-weight: 600;
      color: #333;
    }
  }
  
  .food-detail {
    display: flex;
    gap: 20rpx;
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .food-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 12rpx;
      background: #f0f0f0;
    }
    
    .food-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      
      .food-name {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .food-options {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 10rpx;
      }
      
      .food-price {
        .price {
          font-size: 32rpx;
          font-weight: 700;
          color: #ff4757;
        }
      }
    }
  }
}

.notes-section {
  .notes-input {
    width: 100%;
    min-height: 120rpx;
    background: #f8f9fa;
    border: 2rpx solid #e1e5e9;
    border-radius: 12rpx;
    padding: 20rpx;
    font-size: 28rpx;
    color: #333;
    resize: none;
    
    &:focus {
      border-color: #ff4757;
      background: #fff;
    }
  }
}

// ⭐ 费用明细样式
.price-detail-section {
  background: #fff;
  margin: 20rpx 0;
  padding: 30rpx;
  
  .price-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .price-label {
      font-size: 28rpx;
      color: #666;
    }
    
    .price-value {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }
  }
}

.bottom-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: space-between;
  
  .total-info {
    display: flex;
    align-items: center;
    gap: 10rpx;
    
    .total-label {
      font-size: 28rpx;
      color: #333;
    }
    
    .total-price {
      font-size: 36rpx;
      font-weight: 700;
      color: #ff4757;
    }
  }
  
  .order-btn {
    width: 200rpx;
    height: 80rpx;
    background: linear-gradient(135deg, #ff4757 0%, #ff6b7a 100%);
    color: white;
    border: none;
    border-radius: 40rpx;
    font-size: 28rpx;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:disabled {
      background: #ccc;
      cursor: not-allowed;
    }
    
    &:not(:disabled):active {
      transform: scale(0.98);
    }
  }
}
</style>
